package com.hjx.hibernate;

import com.hjx.objectassert.model.CreditCardAllData;
import org.junit.Test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class HibernateValidator {


    @Test
    public void test() throws ScriptException {
        ScriptEngineManager sm = new ScriptEngineManager();
        ScriptEngine nashorn = sm.getEngineByName("nashorn");
        nashorn.eval("var CreditCardAllData = Java.type(\"com.hjx.objectassert.model.CreditCardAllData\")\n" +
                "var ArrayList = Java.type(\"java.util.ArrayList\")\n" +
                "var LinkedList = Java.type(\"java.util.LinkedList\")\n" +
                "var BillAllData = Java.type(\"com.hjx.objectassert.model.BillAllData\")\n" +
                "var Installment = Java.type(\"com.hjx.objectassert.model.Installment\")\n" +
                "\n" +
                "\n" +
                "var data = new CreditCardAllData()\n" +
                "print(data.getClass())\n" +
                "\n" +
                "var list = new ArrayList()\n" +
                "var billAllData = new BillAllData()\n" +
                "\n" +
                "var installments = new ArrayList()\n" +
                "var installment = new Installment()\n" +
                "installment.setBillId(\"xxxxxxxxxxxxxxxxxxxxxx\")\n" +
                "installments.add(installment)\n" +
                "\n" +
                "billAllData.setInstallments(installments)\n" +
                "list.add(billAllData)\n" +
                "\n" +
                "\n" +
                "data.setBills(list)\n" +
                "\n" +
                "var installments = data.getBills().get(0).getInstallments()\n" +
                "print(installments.getClass())\n" +
                "\n" +
                "\n" +
                "var bugList = new ArrayList()\n" +
                "installments.add(bugList)\n" +
                "print(1)");


        CreditCardAllData creditCardAllData = (CreditCardAllData) nashorn.eval("data");
//        creditCardAllData.setCardType("防守打法双方都");

        List propertyPath = new ArrayList();
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<CreditCardAllData>> set = validator.validate(creditCardAllData);
        for(ConstraintViolation constraintViolation : set){
            propertyPath.add("( " + constraintViolation.getPropertyPath().toString() + " = " + constraintViolation.getInvalidValue() + " )");
        }
        propertyPath.forEach(System.out::println);
    }
}
